import json
from django.http import JsonResponse
from user.models import User
from django.views import View
from user.views import make_token


# 异常10200-10299
class TokenView(View):
    def post(self, request):
        # add your code here
        # 1 获取前端提交的json串
        json_str = request.body
        # 2 将json串反序列化为python对象
        py_obj = json.loads(json_str)
        username = py_obj['username']
        password = py_obj['password']
        # 3 数据为空校验
        if not username or not password:
            result = {'code': 10200, 'error': '用户名或密码为空'}
            return JsonResponse(result)
        # 4 检查用户名是否正确(get try)
        try:
            user = User.objects.get(username=username)
        except:
            result = {'code': 10201, 'error': '用户名或密码错误'}
            return JsonResponse(result)
        # 5 根据用户输入的密码并比对
        if not user.check_password(password):
            result = {'code': 10202, 'error': '用户名或密码错误'}
            return JsonResponse(result)
        # 判断密码是否正确
        # 6 通过验证后,将用户名保存到toke中
        token = make_token(user.id)
        token = token.decode()
        return JsonResponse({
            'code': 200,
            'token': token,
            'data': {
                'username': username,
                'userid': user.id,
                'avatar': str(user.avatar),
                'nickname': user.nickname,
            }
        })
